package com.archie.zhufengfm.utils;

/**
 * Created
 * Author: yuqi
 * Email：inconceivable_man@163.com
 * Date: 2015/10/12
 */

import android.util.Log;

import java.io.*;
import java.net.HttpURLConnection;

/**
 * IO流的工具类
 */
public class StreamUtil {

    private StreamUtil() {

    }

    public static void close(Object stream) {
        if (stream != null) {

            try {
                if (stream instanceof InputStream) {
                    ((InputStream) stream).close();
                } else if (stream instanceof OutputStream) {
                    ((OutputStream) stream).close();
                } else if (stream instanceof Reader) {
                    ((Reader) stream).close();
                } else if (stream instanceof Writer) {
                    ((Writer) stream).close();
                } else if (stream instanceof HttpURLConnection) {
                    ((HttpURLConnection) stream).disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    public static byte[] readStream(InputStream in) throws IOException {
        byte[] ret = null;

        if (in != null) {

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buf = new byte[128];
            int len = -1;

            while ((len = in.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }

            //注意buf必须进行null操作，减少内存溢出的可能性
            buf = null;

            ret = bos.toByteArray();

            bos.close();
        }
        return ret;
    }

}
